package com.whz.workmanageol.utils;

import com.whz.workmanageol.dao.PublishMapper;
import com.whz.workmanageol.entity.Publish;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Component
public class FileDownload {

    private Logger logger = LoggerFactory.getLogger(FileDownload.class);
    // 导入模板下载路径
    public static final String EXCELEXAMLE =
            "F:" + File.separator + "WorkManageOL" + File.separator + "ExcelExample" + File.separator;

    @Autowired
    private PublishMapper publishMapper;
    /**
     * 下载指定publishid下的附件
     * @param publishid
     */
    public String downAttach(String publishid, HttpServletResponse response){
        Publish publish = publishMapper.selectByPrimaryKey(publishid);
//        Publish publish = publishRepository.findById(publishid).get();
        String filename = FileUpload.FILE_UPLOAD_PATH + publish.getFilepath()  + "publish" + File.separator + publish.getSeq() + ".zip";
        download(filename, response);
        return filename;
    }

    /**
     * 下载单个文件
     * @param filename
     * @param response
     */
    private void download(String filename, HttpServletResponse response){
        BufferedInputStream bis = null;
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
//            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(new FileInputStream(new File(filename)));
            int i = bis.read(buff);
            while (i != -1){
                outputStream.write(buff, 0, buff.length);
//                outputStream.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.info("下载附件后 关流失败");
                }
            }
        }
    }

    /**
     * 下载学生导入模板Excel
     */
    public String downStuExcel(HttpServletResponse response){
        String stuExcPath = EXCELEXAMLE + "studentinfo.xlsx";
        download(stuExcPath, response);
        return stuExcPath;
    }
}
